<template>
    <div class="min-h-screen bg-gradient-to-r from-[#006263] to-[#D1FFD1] grid grid-cols-1 md:grid-cols-2">
        <!-- Logo -->
        <div class="absolute top-6 left-6">
            <img src="../../assets/logo.svg" alt="Logo" class="h-20 md:h-24 lg:h-28" />
        </div>

        <!-- 左侧标题和描述 -->
        <div class="hidden md:flex flex-col items-start justify-center text-white pl-28">
            <h1 class="text-6xl font-bold mb-2">地中海贫血筛查平台</h1>
            <p class="text-lg">Thalassemia Screening Platform</p>
        </div>

        <!-- 登录/注册表单 -->
        <div class="flex items-center justify-center p-4">
            <var-loading description="LOADING" :loading="loading" color="#006263">
                <div class="bg-white p-8 md:p-10 rounded-lg shadow-lg relative overflow-hidden form-container"
                    :style="{ width: isRegister ? '500px' : '400px', height: isRegister ? '650px' : '450px' }">
                    <!-- 登录表单 -->
                    <transition name="slide" mode="out-in">
                        <var-form v-if="!isRegister && !showSuccessResult" key="login" ref="loginForm">
                            <h1 class="text-2xl font-bold mb-8 text-center">欢迎登录</h1>
                            <!-- 账号输入框 -->
                            <div class="mb-6">
                                <var-input size="normal" variant="outlined" focus-color="#006263" placeholder="请输入账号"
                                    v-model="loginForm.account"
                                    :rules="[(v) => !!v || '账号不能为空', (v) => /^[a-zA-Z0-9]+$/.test(v) || '账号只能包含字母和数字']" />
                            </div>
                            <!-- 密码输入框 -->
                            <div class="mb-4">
                                <var-input size="normal" variant="outlined" focus-color="#006263" placeholder="请输入密码"
                                    v-model="loginForm.password" type="password" :rules="[(v) => !!v || '密码不能为空']" />
                            </div>
                            <!-- 登录按钮 -->
                            <div class="mb-12 mt-16">
                                <var-button block size="large" color="#006263" text-color="#FFFFFF"
                                    @click="handleLogin">登录</var-button>
                            </div>
                            <!-- 跳转到注册页面的链接 -->
                            <div class="text-center text-sm text-gray-600 mt-8">
                                还没有账号？
                                <a href="#" class="text-[#006263]" @click.prevent="switchToRegister">点击此处立即注册！</a>
                            </div>
                        </var-form>
                        <!-- 注册表单 -->
                        <var-form v-else-if="isRegister && !showSuccessResult" key="register" ref="registerForm">
                            <h1 class="text-2xl font-bold mb-8 text-center">注册账号</h1>
                            <!-- 用户名输入框 -->
                            <div class="mb-3">
                                <var-input size="small" variant="outlined" focus-color="#006263"
                                    placeholder="请输入6位以上由英文字母和数字组成的账号" v-model="registerForm.username"
                                    :rules="[(v) => !!v || '用户名不能为空']" />
                            </div>
                            <!-- 密码输入框 -->
                            <div class="mb-3">
                                <var-input size="small" variant="outlined" focus-color="#006263"
                                    placeholder="请输入6位以上由英文字母和数字组成的密码" v-model="registerForm.password" type="password"
                                    :rules="[(v) => !!v || '密码不能为空']" />
                            </div>
                            <!-- 真实姓名输入框 -->
                            <div class="mb-3">
                                <var-input size="small" variant="outlined" focus-color="#006263" placeholder="请输入真实姓名"
                                    v-model="registerForm.realName" :rules="[(v) => !!v || '真实姓名不能为空']" />
                            </div>
                            <!-- 邮箱输入框 -->
                            <div class="mb-3">
                                <var-input size="small" variant="outlined" focus-color="#006263" placeholder="请输入邮箱"
                                    v-model="registerForm.email"
                                    :rules="[(v) => !!v || '邮箱不能为空', (v) => /.+@.+\..+/.test(v) || '邮箱格式不正确']" />
                            </div>
                            <!-- 电话输入框 -->
                            <div class="mb-3">
                                <var-input size="small" variant="outlined" focus-color="#006263" placeholder="请输入电话"
                                    v-model="registerForm.phone"
                                    :rules="[(v) => !!v || '电话不能为空', (v) => /^\d{11}$/.test(v) || '电话格式不正确']" />
                            </div>
                            <!-- 身份选择框 -->
                            <div class="mb-4">
                                <var-select size="small" variant="outlined" focus-color="#006263" placeholder="请选择身份"
                                    v-model="registerForm.role" :rules="[(v) => !!v || '请选择身份']">
                                    <var-option label="医生" value="YS" />
                                    <var-option label="科研人员" value="KYRY" />
                                </var-select>
                            </div>
                            <!-- 注册按钮 -->
                            <div class="mb-6">
                                <var-button block color="#006263" text-color="#FFFFFF"
                                    @click="handleRegister">注册</var-button>
                            </div>
                            <!-- 返回登录页面的链接 -->
                            <div class="text-center text-sm text-gray-600">
                                已有账号？
                                <a href="#" class="text-[#006263]" @click.prevent="switchToLogin">点击此处登录！</a>
                            </div>
                        </var-form>
                    </transition>
                    <var-result class="h-full flex items-center justify-center" v-model:show="showSuccessResult"
                        key="success" type="success" :title="successTitle" :description="successDescription">
                        <template #footer>
                            <a v-if="successTitle === '注册成功'" href="#" class="text-[#006263]"
                                @click.prevent="switchToLogin">点击此处登录！</a>
                        </template>
                    </var-result>
                </div>
            </var-loading>
        </div>

        <!-- 弹窗 -->
        <var-dialog confirm-button-text-color="#006263" cancel-button-text-color="#006263" v-model:show="showDialog"
            title="提示" :message="dialogMessage" />
    </div>
</template>

<script>

export default {
    name: 'LoginPage',
    data() {
        return {
            isRegister: false,
            showDialog: false,
            dialogMessage: '',
            showSuccessResult: false,
            successTitle: '',
            successDescription: '',
            loading: false,
            loginForm: {
                account: '',
                password: ''
            },
            registerForm: {
                username: '',
                password: '',
                realName: '',
                email: '',
                phone: '',
                role: ''
            }
        };
    },
    methods: {
        switchToRegister() {
            this.isRegister = true;
            this.$nextTick(() => {
                if (this.$refs.loginForm) {
                    this.$refs.loginForm.reset(); // 🌈 优化点：同时重置登录表单
                }
                if (this.$refs.registerForm) {
                    this.$refs.registerForm.reset(); // 重置注册表单验证
                }
            });
        },
        switchToLogin() {
            this.isRegister = false;
            this.showSuccessResult = false; // 确保切换到登录表单
            this.$nextTick(() => {
                if (this.$refs.loginForm) {
                    this.$refs.loginForm.reset(); // 重置登录表单验证
                }
            });
        },
        async handleLogin() {
            this.loading = true;
            const res = await this.$api.auth.login({
                account: this.loginForm.account,
                password: this.loginForm.password
            });
            this.loading = false;
            if (res.success) {
                this.successTitle = '登录成功';
                this.successDescription = '欢迎！';
                localStorage.setItem('token', res.data); // 保存token到本地存储
                this.$store.user.clearUserInfo();
                await this.$store.user.decodeToken();
                this.showSuccessResult = true;
                // 2秒后跳转到首页
                setTimeout(() => {
                    this.$router.push('/user/home');
                    this.$refs.loginForm.reset();
                }, 1000);
            } else {
                this.dialogMessage = '账号或密码错误！';
                this.showDialog = true;
            }
        },
        async handleRegister() {
            // 使用表单验证代替手动校验
            const valid = await this.$refs.registerForm?.validate();
            if (!valid) return;
            this.loading = true;
            const res = await this.$api.auth.register({
                account: this.registerForm.username,
                password: this.registerForm.password,
                name: this.registerForm.realName,
                email: this.registerForm.email,
                phone: this.registerForm.phone,
                identity: this.registerForm.role
            });
            this.loading = false;
            if (res.success) {
                this.successTitle = '注册成功';
                this.showSuccessResult = true; 
                this.$refs.registerForm.reset(); // 注册成功后自动清空表单
            } else {
                this.dialogMessage = res.error;
                this.showDialog = true;
            }
        }
    }
};
</script>

<style scoped>
/* 添加一些微调和定制 */
.form-container {
    transition: all 0.3s ease-in-out;
}

/* 滑动过渡效果 */
.slide-enter-active,
.slide-leave-active {
    transition: all 0.2s ease;
}

.slide-enter-from {
    transform: translateX(100%);
    opacity: 0;
}

.slide-leave-to {
    transform: translateX(-100%);
    opacity: 0;
}
</style>
